/* eslint-disable */
// @ts-check
const validate = require("./swagger-validate");
const { filterPaths, filterDefinitions } = require("./swagger-filter");
const { baseConfig, configs } = require('./configs');
const path = require('path');
const request = require("request");

const apiName = process.env.API_NAME;
if (!apiName) { throw new Error('没有传入node环境变量"API_NAME"。') }

const config = configs[apiName];
if (!config) { throw new Error(`无法找到服务"${apiName}"的配置。`); }

let rawSwagger = undefined;
if (config.swaggerUrl !=='')
  rawSwagger = require(baseConfig.swaggerPath(apiName));

console.log(`开始生成服务"${apiName}"的代码。`);

module.exports = {
  url: baseConfig.localUrl(apiName),
  remoteUrl: path.relative(process.cwd(), baseConfig.yapiPath(apiName)),
  type: "yapi",
  validateResponse: true,
  swaggerConfig: {
    /**
     *
     * @param {import("auto-service/lib/consts").SwaggerJson} swagger
     * @returns
     */
    modifier: (swagger) => {
      console.log(`--- 开始处理 swagger json`);

      // 通过 path 过滤 api
      if (config.paths) {
        console.log(`--- 过滤 path`);
        swagger.paths = filterPaths(swagger.paths, config.paths);
      }

      // 添加 definitions
      // TODO 根据api自己查找，而不是写死
      if (config.definitions && rawSwagger !== undefined) {
        console.log(`--- 添加 definitions`);
        swagger.definitions = filterDefinitions(rawSwagger.definitions, config.definitions);
      }

      // 验证中文等
      console.log(`--- 处理中文和无效参数`);
      validate(swagger);

      console.log(`--- 处理 swagger json 完毕`);
      return swagger;
    },
  },
  swaggerParser: {
    "-o": `src/services/${apiName}`,
  },
};
